/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_orm.htm
 *
 * Zhiqim ORM is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.orm.dbo.condition;

import org.zhiqim.kernel.model.maps.MapSO;
import org.zhiqim.kernel.util.Asserts;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Condition;
import org.zhiqim.orm.dbo.Dbo;
import org.zhiqim.orm.dbo.DboField;

/**
 * 函数条件，如where left(field, 3) = 'Z01'
 *
 * @version v8.0.4 @author zouzhigang 2022-4-25 新建与整理
 */
public class _Function extends Condition
{
    private String function;
    private String value;
    private String condition;
    
    public _Function(String function, String value, String condition)
    {
        this.function = function;
        this.value = value;
        this.condition = condition;
    }
    
    @Override
    public boolean match(Object obj)
    {
        throw Asserts.exception("暂不支持函数匹配");
    }

    @Override
    public String toSql(Dbo dbo, MapSO paramMap) throws ORMException
    {
        //对函数中可能出现的字段进行匹配，替换成表列，注意有可能第二个列名会包含第一个列名，因此处理时字段名从长到短进行匹配
        DboField[] dboFieldArr = dbo.getFieldColumnListOrderByLen();
        for (DboField dboField : dboFieldArr)
        {//依次从长到短对函数中的字段替换成表列 TODO 暂不对$等可能替换成错进行处理
            function = function.replaceAll(dboField.getField(), dboField.getColumn());
        }

        int ind = paramMap.size();
        String paramKey = "_function_"+ind;
        paramMap.put(paramKey, convertValue(value));//把值放到表中，后续方便把##转成?号，然后再设置值
        
        return new StringBuilder()
            .append(function).append(_SPACE_).append(condition).append(_SPACE_)
            .append("#").append(paramKey).append("#")
            .toString();
    }
}
